<template>
    <el-dialog v-model="isShow" :align-center="true" :width="width" :close-on-click-modal="false" :destroy-on-close="true">
        <template #header="{ titleClass }">
            <span :class="titleClass">导入</span>
            <el-divider />
            <el-space alignment="center">
                <el-upload class="upload-box" :show-file-list="false" :http-request="onUploadRequest">
                    <BaseButton type="info" icon-name="icon-import">导入</BaseButton>
                </el-upload>
                <BaseButton type="info" icon-name="icon-export" @click="onExportTemplate">导出模版</BaseButton>
            </el-space>
        </template>

        <el-table :data="dataArr" ref="tableRef" height="500" border stripe>
            <TableColumns
                :columns="columnArr ?? []"
                :column-action-types="[]"
                :isShowOverflowTooltip="false"
                :isFixed="false"
                :is-enabled-width="false"
                :is-switch="false"
                :isEnabledComponent="false"
            >
                <template #columnAppend>
                    <el-table-column label="操作">
                        <template #default="{ $index }">
                            <BaseButton link type="danger" icon-name="icon-delete" @click="onDelete($index)">删除</BaseButton>
                        </template>
                    </el-table-column>
                </template>
            </TableColumns>
        </el-table>

        <template #footer>
            <BaseButton @click="onCancel">取消</BaseButton>
            <BaseButton @click="onConfirm" type="primary">确认</BaseButton>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { UserForm } from '@/api/auth/user/type'
import { formatAddress, formatBoolean, formatGender, formatNumber, formatString } from '@/utils/format'
import { UploadRequestHandler, UploadRequestOptions } from 'element-plus'
import * as XLSX from 'xlsx'

interface Props {
    columns: TableColumnType<any>[]
    width: string | number
    uploadAction: string
}
const props = withDefaults(defineProps<Partial<Props>>(), {
    width: '75%',
})
const emit = defineEmits<{ onTableAction: [action: TableActionType, params: any] }>()
const isShow = ref(false)
const dataArr = ref()
const columnArr = computed(() =>
    props.columns?.filter((item) => item.type !== 'selection' && item.type !== 'actions' && item.prop !== 'createDateTime' && item.prop !== 'avatar'),
)

const onDelete = ($index: number) => {
    ElMessageBox.confirm('确定要删除这条数据吗？', {
        title: '提示',
        type: 'warning',
    })
        .then(async () => {
            dataArr.value = dataArr.value.filter((item: any, index: number) => index !== $index)
            ElMessage.success('删除成功')
        })
        .catch((error) => {
            if (error === 'cancel') {
                ElMessage.info('已取消删除')
            } else {
                ElMessage.warning('删除失败')
            }
        })
}
const onExportTemplate = () => {
    emit('onTableAction', 'export-excelTemplate', {})
}
const onUploadRequest = async (options: UploadRequestOptions): Promise<UploadRequestHandler | undefined> => {
    // 定义允许的Excel文件MIME类型和扩展名
    const excelMimeTypes = [
        'application/vnd.ms-excel', // .xls
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
    ]
    const excelExtensions = ['xls', 'xlsx']
    // 获取文件扩展名（不区分大小写）
    const fileExtension = options.file.name.split('.').pop()?.toLowerCase()
    // 检查文件扩展名是否在允许的列表中
    const isExcelExtension = fileExtension && excelExtensions.includes(fileExtension)
    // 检查MIME类型是否在允许的列表中
    const isExcelMimeType = excelMimeTypes.includes(options.file.type)

    if (!isExcelExtension || !isExcelMimeType) {
        ElMessage.error('上传的文件必须是 Excel 格式 (XLS | XLSX)！')
        return
    }

    const reader = new FileReader()
    reader.readAsArrayBuffer(options.file)
    reader.onload = function (ev: ProgressEvent<FileReader>) {
        const fileData = ev?.target?.result
        if (fileData) {
            const workbook = XLSX.read(fileData, { type: 'binary' })
            // 假设第一个工作表是所需的数据表
            const first_sheet_name = workbook.SheetNames[0]
            // 将工作表转换为JSON格式
            const excelData = XLSX.utils.sheet_to_json(workbook.Sheets[first_sheet_name])
            const stringData = JSON.stringify(excelData).replace(/（/g, '(').replace(/）/g, ')')
            const data = JSON.parse(stringData)
            const mappedData: Partial<UserForm>[] = []
            data.forEach((item: any, index: number, arr: any) => {
                const name = formatString(arr[index]['Name'])
                if (name === '') {
                    ElMessage.warning('名称不可为空')
                }
                const email = formatString(arr[index]['Email'])
                if (email === '') {
                    ElMessage.warning('邮箱不可为空')
                }
                const phoneNumber = formatString(arr[index]['PhoneNumber'])
                if (phoneNumber === '') {
                    ElMessage.warning('电话不可为空')
                }
                if (name && email && phoneNumber) {
                    const user: Partial<UserForm> = {
                        name: name,
                        nickName: formatString(arr[index]['NickName']),
                        email: email,
                        phoneNumber: phoneNumber,
                        gender: formatString(arr[index]['Gender']),
                        age: formatNumber(arr[index]['Age']),
                        address: formatAddress(arr[index]['Address']),
                        description: formatString(arr[index]['Description']),
                        isEnabled: formatBoolean(arr[index]['IsEnabled']),
                    }
                    mappedData.push(user)
                }
            })
            dataArr.value = mappedData
        }
    }
}

const onOpenDialog = () => (isShow.value = true)

const onCloseDialog = () => (isShow.value = false)

const onCancel = () => onCloseDialog()

const onConfirm = async () => {
    if (dataArr.value && dataArr.value.length !== 0) {
        const data: any[] = []
        dataArr.value.forEach((item: any) => {
            data.push({ ...item, gender: formatGender(item.gender) })
        })
        emit('onTableAction', 'import-form-submit', { users: data })
    }
}
defineExpose({
    onOpenDialog,
    onCloseDialog,
})
</script>

<style lang="scss" scoped>
.upload-box {
    display: flex;
}
</style>
